package com.hu.web.servlet;

import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;

public class HelloServlet implements Servlet {

    public HelloServlet() {
        System.out.println("HelloServlet 的构造方法执行");
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
//        System.out.println("HelloServlet 的 init 方法执行");

        // 获取 Servlet 名称: web.xml 中配置 servlet-name 的值
//        String servletName = servletConfig.getServletName();
//        System.out.println(servletName);

        // 获取全局上下文 ServletContext 对象
//        ServletContext servletContext = servletConfig.getServletContext();
//        System.out.println(servletContext);

        // 获取 Servlet 初始化参数
//        String path = servletConfig.getInitParameter("path");
//        System.out.println(path);
//        String initParameter = servletConfig.getInitParameter("init-param");
//        System.out.println(initParameter);
//        Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
//        while (initParameterNames.hasMoreElements()){
//            System.out.println(initParameterNames.nextElement());
//        }
    }

    // 处理客户端的请求和响应
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        ServletContext servletContext = servletRequest.getServletContext();
        System.out.println(servletContext);

        // 获取项目的上下文路径(带 / 的项目名)
        String contextPath = servletContext.getContextPath();
        System.out.println("contextPath: " + contextPath);
        // 获取虚拟路径所映射的本地真实路径(根据相对路径获取绝对路径)
        String realPath = servletContext.getRealPath("/upload");
        System.out.println("realPath: " + realPath);
        // 获取 WEB 应用程序的全局初始化参数
        String servletContextInitParamKey = servletContext.getInitParameter("ServletContextInitParamKey");
        System.out.println("ServletContextInitParamKey: " + servletContextInitParamKey);
        String globalConfig = servletContext.getInitParameter("GlobalConfig");
        System.out.println("globalConfig: " + globalConfig);
        Enumeration<String> initParameterNames = servletContext.getInitParameterNames();
        while (initParameterNames.hasMoreElements()){
            System.out.println(initParameterNames.nextElement());
        }

        System.out.println("HelloServlet 的 service 方法执行");
    }

    @Override
    public void destroy() {
        System.out.println("HelloServlet 的 destroy 方法执行");

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public String getServletInfo() {
        return null;
    }
}
